package net.amitabul.slrclub;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class UsedMarket {
	
	private String id = null;
	private String password = null;

	private DefaultHttpClient client = null;
	
	public UsedMarket(String id, String password) {
		this.client = new DefaultHttpClient();
		this.id = id;
		this.password = password;
	}
	
	private void login() throws ClientProtocolException, IOException {
		HttpPost httpPost = new HttpPost("http://m.slrclub.com/login/process.php");
		// header
		Header[] headers = new Header[] {
				 //new BasicHeader("X-Requested-With", "XMLHttpRequest"), 
				 new BasicHeader("Referer", "http://m.slrclub.com/?type=login")};		
		httpPost.setHeaders(headers);
		
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
		nameValuePairs.add(new BasicNameValuePair("user_id", this.id));
		nameValuePairs.add(new BasicNameValuePair("password", this.password));
		nameValuePairs.add(new BasicNameValuePair("r_url", "http%3A%2F%2Fm.slrclub.com%2F"));
		nameValuePairs.add(new BasicNameValuePair("ip_secure", "global"));
		nameValuePairs.add(new BasicNameValuePair("express_login", "basic"));
		nameValuePairs.add(new BasicNameValuePair("x", "72"));
		nameValuePairs.add(new BasicNameValuePair("y", "15"));

		httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				
		client.execute(httpPost);
	}
	private void loadMarket() throws ClientProtocolException, IOException {		
		HttpResponse response = client.execute(new HttpPost("http://m.slrclub.com/l/used_market/?category=1"));
		HttpEntity resEntity = response.getEntity();
		String html = EntityUtils.toString(resEntity);
		
		ParseUsedMarket parse = new ParseUsedMarket(html);
		parse.parsing();
	}
	public void run() {
		try {
			this.login();
			
			this.loadMarket();
			
			
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.d("System", e.toString());
		}
	}
}
